package com.example.t9v25;

import java.net.URL;
import java.util.*;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

public class HelloController {

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;

    @FXML
    private TextField arrayTF;

    @FXML
    private Button clearBtn;

    @FXML
    private Label resLabel;

    @FXML
    private Button solveBtn;

    @FXML
    void clearClick(ActionEvent event) {
        arrayTF.setText("");
    }

    @FXML
    void solveClick(ActionEvent event) {
        List<Integer> li = Arrays.stream(arrayTF.getText().split(" ")).map(Integer::parseInt).toList();
        resLabel.setText(createNewList(li).toString());
    }

    @FXML
    void initialize() {
        assert arrayTF != null : "fx:id=\"arrayTF\" was not injected: check your FXML file 'hello-view.fxml'.";
        assert clearBtn != null : "fx:id=\"clearBtn\" was not injected: check your FXML file 'hello-view.fxml'.";
        assert resLabel != null : "fx:id=\"resLabel\" was not injected: check your FXML file 'hello-view.fxml'.";
        assert solveBtn != null : "fx:id=\"solveBtn\" was not injected: check your FXML file 'hello-view.fxml'.";

    }

    public List<Integer> createNewList(List<Integer> list) {
        List<Integer> sortedList = new ArrayList<>(list);
        sort(sortedList);
        int[] lengths = new int[list.size()];
        int[] parents = new int[list.size()];
        int maxLength = 0;
        int maxIndex = 0;

        for (int i = 0; i < sortedList.size(); i++) {
            lengths[i] = 1;
            parents[i] = -1;
            for (int j = 0; j < i; j++) {
                if (sortedList.get(j) + 1 == sortedList.get(i) && lengths[j] + 1 > lengths[i]) {
                    lengths[i] = lengths[j] + 1;
                    parents[i] = j;
                }
            }
            if (lengths[i] > maxLength) {
                maxLength = lengths[i];
                maxIndex = i;
            }
        }

        List<Integer> result = new ArrayList<>();
        while (maxIndex != -1) {
            result.add(sortedList.get(maxIndex));
            maxIndex = parents[maxIndex];
        }
        Collections.reverse(result);
        return result;
    }

    public void sort(List<Integer> list) {
        List<Integer> sortedList = new ArrayList<>(list);
        Collections.sort(sortedList);
        for (int i = 0; i < list.size(); i++) {
            list.set(i, sortedList.get(i));
        }
    }

}
